class MyPromise {
  constructor(executor) {
    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = []
    const self = this
    function resolve(data) {
      if (self.PromiseState !== 'pending') return
      self.PromiseState = 'fulfilled'
      self.PromiseResult = data
      setTimeout(() => {
        self.callbacks.forEach(item => {
          item.onResovled(data)
        })
      })
    }
    function reject(data) {
      if (self.PromiseState !== 'pending') return
      self.PromiseState = 'rejected'
      self.PromiseResult = data
      setTimeout(() => {
        self.callbacks.forEach(item => {
          item.onRejected(data)
        })
      })
    }
    try {
      executor(resolve, reject)
    } catch (e) {
      reject(e)
    }
  }

  then (onResovled, onRejected) {
    const self = this
    if (typeof onRejected !== 'function') {
      onRejected = reason => {
        throw reason
      }
    }
    if (typeof onResovled !== 'function') {
      onResovled = value => value
    }
    return new MyPromise((resolve, reject) => {
      // 封装函数
      function callback(type) {
        try {
          let result = type(self.PromiseResult)
          if (result instanceof MyPromise) {
            result.then(v => {
              resolve(v)
            }, r => {
              reject(r)
            })
          } else {
            // 结果的对象状态为成功
            resolve(result)
          }
        } catch(e) {
          reject(e)
        }
      }
      // 调用回调函数
      //也可以先改状态再指定回调（同步任务）
      if (this.PromiseState === 'fulfilled') {
        // 将then变为异步的
        setTimeout(() => callback(onResovled))
      }
      if (this.PromiseState === 'rejected') {
        // 将then变为异步的
        setTimeout(() => callback(onRejected))
      }
      //先指定回调再改变状态（异步任务）
      if (this.PromiseState === 'pending') {
        // 保存回调函数，状态不确定
        // 这样保存回调不对，只能保存最后一个，前面的会被覆盖
        // this.callback = {
        //   onResovled,
        //   onRejected
        // }
        this.callbacks.push({
          onResovled: function() {
            callback(onResovled)
          },
          onRejected: function() {
            callback(onRejected)
          }
        })
      }
    })
  }

  catch (onRejected) {
    return this.then(undefined, onRejected)
  }
  // 属于类不属于实例对象
  static resolve (value) {
    return new MyPromise((resolve, reject) => {
      if (value instanceof MyPromise) {
        value.then(v => resolve(v), r => reject
        (r) )
      } else {
        resolve(value)
      }
    })
  }

  static reject (value) {
    return new MyPromise((resolve, reject) => {
      reject(value)
    })
  }

  static all (promises) {
    return new MyPromise((resolve, reject) => {
      let count = 0
      let arr = []
      promises.forEach((promise,index) => promise.then(
        v => {
          // 成功对象会调用
          count++
          arr[index] = v
          if (count === promises.length) {
            // 修改状态
            resolve(arr)
          }
        },
        r => {
          reject(r)
        }
      ))
    })
  }

  static race (promises) {
    return new MyPromise((resolve, reject) => {
      promises.forEach((promise, index) => {
        promise.then(v => {
          resolve(v)
        }, r => {
          reject(r)
        })
      })
    })
  }
}